package com.yricky.memoria.ui.component

import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.yricky.memoria.R
import com.yricky.memoria.data.Section
import com.yricky.memoria.data.pojo.PdfQuery
import com.yricky.memoria.data.pojo.SectionQuery
import com.yricky.memoria.ui.component.common.*
import com.yricky.memoria.ui.dialog.showComposeDialog
import com.yricky.memoria.ui.dialog.showGetStrDialog
import com.yricky.memoria.ui.theme.Shapes
import com.yricky.memoria.ui.theme.ThemeInst
import com.yricky.memoria.utils.PdfDoc
import com.yricky.memoria.utils.gson
import com.yricky.memoria.utils.startPdfActivity
import com.yricky.memoria.utils.startSectionActivity

/**
 * @author Yricky
 * @date 2021/11/27
 */

@Composable
fun SectionActivityContent(viewModel: SectionViewModel){
    ThemeInst.Material {
        val viewState by viewModel.viewState.collectAsState()
        Column(modifier = Modifier.fillMaxSize()) {
            Title(viewState.title){ expandState ->
                MenuItems.Edit(
                    state = expandState,
                    callback = {
                        viewModel.onAction(SectionViewModel.Action.EditMode(!viewState.isEditMode))
                    }
                )
            }
            Column(
                Modifier
                    .weight(1f)
                    .verticalScroll(rememberScrollState())){
                viewState.items.forEach { item->
                    Box {
                        when(item.type){
                            Section.Item.TYPE_IMG -> ImgItem(viewModel = viewModel, item = item)
                            Section.Item.TYPE_TEXT -> TextItem(viewModel = viewModel, item = item)
                            Section.Item.TYPE_SECTION -> SectionItem(
                                viewModel = viewModel,
                                item = item
                            )
                            Section.Item.TYPE_PDF -> PdfItem(viewModel = viewModel, item = item)
                        }
                    }

                }
                ListTail(viewModel)
            }
        }
    }

}
@Composable
fun RowScope.CommonEditItem(viewModel: SectionViewModel,item: Section.Item,buttons:@Composable RowScope.()->Unit = {}){
    Icon(imageVector = Icons.Rounded.KeyboardArrowUp,
        contentDescription = "",
        modifier = Modifier.clickable { viewModel.onAction(SectionViewModel.Action.MoveItem(item,true)) }
    )
    Icon(imageVector = Icons.Rounded.KeyboardArrowDown,
        contentDescription = "",
        modifier = Modifier.clickable { viewModel.onAction(SectionViewModel.Action.MoveItem(item,false)) }
    )
    buttons(this)
    Spacer(modifier = Modifier.weight(1f))
    Icon(imageVector = Icons.Rounded.Delete,
        contentDescription = "",
        modifier = Modifier.clickable { viewModel.onAction(SectionViewModel.Action.RemoveItem(item)) }
    )
}

@Composable
fun TextItem(viewModel: SectionViewModel,item: Section.Item){
    val viewState by viewModel.viewState.collectAsState()
    ItemContentFrameLimited(
        isEdit = viewState.isEditMode,
        contentEdit = { CommonEditItem(viewModel = viewModel, item = item) },
        content = {
        if(viewState.isEditMode){
            var str by remember { mutableStateOf(item.content) }
            OutlinedTextField(
                modifier = Modifier.weight(1f),
                value = str,
                textStyle = TextStyle(),
                onValueChange = {
                    item.content = it
                    viewModel.onAction(SectionViewModel.Action.Save)
                    str = it
                }
            )
        }else{
            Text(text = item.content)
        }

    })
}

@Composable
fun ImgItem(viewModel: SectionViewModel,item: Section.Item){
    val viewState by viewModel.viewState.collectAsState()
    ItemContentFrameLimited(
        isEdit = viewState.isEditMode,
        contentEdit = { CommonEditItem(viewModel = viewModel, item = item) },
    ){
        Box(modifier = Modifier.fillMaxWidth(),
            contentAlignment = Alignment.Center){
            PathImage(imagePath = viewModel.getContentPath(item.content))
        }
    }
}

@Composable
fun SectionItem(viewModel: SectionViewModel,item: Section.Item){
    val viewState by viewModel.viewState.collectAsState()
    ItemContentFrameLimited(
        isEdit = viewState.isEditMode,
        contentEdit = { CommonEditItem(viewModel = viewModel, item = item) },
    ){
        val query:SectionQuery? = try {
            gson.fromJson(item.content,SectionQuery::class.java)
        }catch (e:Throwable){
            null
        }
        val context = LocalContext.current
        query?.let{
            Surface(shape = Shapes.small) {
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .clickable { context.startSectionActivity(it) }
                    .padding(8.dp)

                ) {
                    Icon(imageVector = ImageVector.vectorResource(id = R.drawable.ic_round_section_24), contentDescription = "")
                    Text(text = it.sectionMetaData.name)
                }
            }

        }

    }
}

@Composable
fun PdfItem(viewModel: SectionViewModel,item: Section.Item){
    val viewState by viewModel.viewState.collectAsState()
    ItemContentFrameLimited(
        isEdit = viewState.isEditMode,
        contentEdit = { CommonEditItem(viewModel = viewModel, item = item) },
    ){
        val query:PdfQuery? = try {
            gson.fromJson(item.content,PdfQuery::class.java)
        }catch (e:Throwable){
            null
        }
        val context = LocalContext.current
        query?.let{
            Surface(shape = Shapes.small) {
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .clickable { context.startPdfActivity(it) }
                    .padding(8.dp)
                ) {
                    Icon(imageVector = ImageVector.vectorResource(id = R.drawable.ic_round_pdf_24), contentDescription = "")
                    Text(text = it.pdfName)
                }
            }

        }

    }
}



@Preview(showBackground = true)
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun ListTail(viewModel: SectionViewModel = SectionViewModel()){
    val viewState by viewModel.viewState.collectAsState()
    val context = LocalContext.current
    Column {
        Spacer(modifier = Modifier.height(64.dp))

        if(viewState.items.size < 32 && viewState.isEditMode){
            ItemContentFrameLimited {
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center) {
                    Row {
                        var show by remember { mutableStateOf(false) }
                        FloatingActionButton(
                            onClick = {show = !show}
                        ){
                            if (show)
                                Icon(imageVector = Icons.Rounded.ArrowBack, contentDescription = "")
                            else
                                Icon(imageVector = Icons.Rounded.Add, contentDescription = "")
                        }
                        AnimatedVisibility(visible = show) {
                            Row {
                                val launcher = rememberLauncherForActivityResult(
                                    ActivityResultContracts.OpenDocument()) {
                                    it?.let{
                                        context.contentResolver.openInputStream(it)?.let{
                                            viewModel.onAction(SectionViewModel.Action.AddImgItem(inS=it))
                                        }
                                    }
                                }
                                FloatingActionButton(
                                    onClick = {
                                        showComposeDialog(context){ dlg ->
                                            LazyColumn{
                                                item {
                                                    Row(modifier = Modifier
                                                        .fillMaxWidth()
                                                        .clickable {
                                                            viewModel.onAction(SectionViewModel.Action.AddTextItem())
                                                            dlg.dismiss()
                                                        }
                                                        .padding(8.dp),
                                                        verticalAlignment = Alignment.CenterVertically
                                                    ) {
                                                        Spacer(modifier = Modifier.weight(1f))
                                                        Text(text = "添加空白")
                                                        Spacer(modifier = Modifier.weight(1f))
                                                    }
                                                }
                                                viewModel.wsModel?.getItems()?.let {
                                                    items(it) {
                                                        Surface(
                                                            shape = Shapes.small,
                                                            modifier = Modifier.padding(8.dp)
                                                        ) {
                                                            Row(
                                                                modifier = Modifier
                                                                    .fillMaxWidth()
                                                                    .clickable {
                                                                        viewModel.onAction(
                                                                            SectionViewModel.Action.AddTextItem(
                                                                                content = it.content
                                                                            )
                                                                        )
                                                                        dlg.dismiss()
                                                                    }
                                                                    .padding(8.dp)
                                                            ) {
                                                                Text(text = it.content)
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }
                                ){ Icon(imageVector = Icons.Rounded.Edit, contentDescription = "") }
                                FloatingActionButton(
                                    onClick = { launcher.launch(arrayOf("image/*")) }
                                ){ Icon(imageVector = ImageVector.vectorResource(R.drawable.ic_round_image_24), contentDescription = "") }
                                FloatingActionButton(
                                    onClick = { 
                                        showGetPdfDialog(context,viewState.pdfList){
                                            viewModel.onAction(SectionViewModel.Action.AddPdfPageItem(pdfName = it.first))
                                        } 
                                    }
                                ){ Icon(imageVector = ImageVector.vectorResource(R.drawable.ic_round_pdf_24), contentDescription = "") }
                                FloatingActionButton(
                                    onClick = {
                                        showGetStrDialog(context,"输入章节请求"){
                                            try {
                                                gson.fromJson(it,SectionQuery::class.java)
                                            }catch (e:Throwable){ null }?.let{
                                                viewModel.onAction(SectionViewModel.Action.AddSectionItem(query = it))
                                            }
                                        }
                                    }
                                ){ Icon(imageVector = ImageVector.vectorResource(R.drawable.ic_round_section_24), contentDescription = "") }
                            }
                        }

                    }

                }
            }
        }

        Spacer(modifier = Modifier.height(64.dp))
    }
}


fun showGetPdfDialog(context: Context, pdfList:List<Pair<String,PdfDoc>>, callback:(Pair<String,PdfDoc>)->Unit){
    showComposeDialog(context) { dlg ->
        Column(
            modifier = Modifier
                .wrapContentHeight()
                .padding(12.dp, 12.dp)
        ) {
            HorizontalPdfList(
                list = pdfList,
                onItemClick = {
                    // 选中PDF
                    callback(it)
                    dlg.dismiss()
                }
            )
        }
    }
}